package com.itheima.pinda.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.j2cache.annotation.Cache;
import com.itheima.j2cache.annotation.CacheEvictor;
import com.itheima.pinda.common.utils.PageResponse;
import com.itheima.pinda.common.utils.Result;
import com.itheima.pinda.DTO.entity.AddressBook;
import com.itheima.pinda.service.IAddressBookService;
import lombok.extern.slf4j.Slf4j;
import net.oschina.j2cache.CacheChannel;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/addressbook")
public class AddressBookController {
    @Autowired
    private IAddressBookService iAddressBookService;

    @Autowired
    private CacheChannel channel;
    // 保存到指定名字的区域
    private String region="addressBook";

    /**
     *  新增地址簿
     */
    @PostMapping("")
    public Result queryAddressBookAll(@RequestBody AddressBook book){
        if(1 == book.getIsDefault()){
            iAddressBookService.lambdaUpdate().set(AddressBook::getIsDefault,0)
                    .eq(AddressBook::getUserId, book.getUserId()).update();
        }
        boolean save = iAddressBookService.save(book);
        if(save){
            //载入缓存
            channel.set(region,book.getId(),book);
            return Result.ok();
        }
        return Result.error();
    }
    /**
     * 查询地址簿详情
     *
     * @param id
     * @return
     */
    @GetMapping("detail/{id}")
    @Cache(region = "addressBook",key = "ab",params = "id")
    public AddressBook detail(@PathVariable(name = "id") String id) {
        AddressBook addressBook = iAddressBookService.getById(id);
        return addressBook;
    }

    /**
     * 分页查询
     *
     */
    @GetMapping("page")
    public PageResponse<AddressBook> page(Integer page, Integer pageSize, String userId, String keyword) {
        Page<AddressBook> iPage = new Page(page, pageSize);
        Page<AddressBook> pageResult = iAddressBookService.lambdaQuery()
                .eq(StringUtils.isNotEmpty(userId), AddressBook::getUserId, userId)
                .and(StringUtils.isNotEmpty(keyword), wrapper ->
                        wrapper.like(AddressBook::getName, keyword).or()
                                .like(AddressBook::getPhoneNumber, keyword).or()
                                .like(AddressBook::getCompanyName, keyword))
                .page(iPage);

        return PageResponse.<AddressBook>builder()
                .items(pageResult.getRecords())
                .page(page)
                .pagesize(pageSize)
                .pages(pageResult.getPages())
                .counts(pageResult.getTotal())
                .build();
    }

    /**
     * 修改
     *
     */
    @PutMapping("/{id}")
    @CacheEvictor(value = {@Cache(region = "addressBook",key = "ab",params = "1.id")})
    public Result update(@PathVariable(name = "id") String id, @RequestBody AddressBook entity) {
        entity.setId(id);
        if (1 == entity.getIsDefault()) {
            iAddressBookService.lambdaUpdate().set(AddressBook::getIsDefault, 0).eq(AddressBook::getUserId, entity.getUserId()).update();
        }
        boolean result = iAddressBookService.updateById(entity);
        if (result) {
            return Result.ok();
        }
        return Result.error();
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @CacheEvictor({@Cache(region = "addressBook",key = "ab",params = "id")})
    public Result del(@PathVariable(name = "id") String id) {
        boolean result = iAddressBookService.removeById(id);
        if (result) {
            return Result.ok();
        }
        return Result.error();
    }


    /**
     * 查询所有
     *
     */
    @GetMapping("all")
    public List<AddressBook> page(@RequestParam String userId, @RequestParam String keyword) {
        List<AddressBook> records = iAddressBookService.lambdaQuery()
                .eq(StringUtils.isNotEmpty(userId), AddressBook::getUserId, userId)
                .and(StringUtils.isNotEmpty(keyword), wrapper ->
                        wrapper.like(AddressBook::getName, keyword).or()
                                .like(AddressBook::getPhoneNumber, keyword).or()
                                .like(AddressBook::getCompanyName, keyword)).list();

        return records;
    }

    /**
     * 查询所有
     *
     */
    @GetMapping("/queryDefaultAddressByUserId")
    public AddressBook page(@RequestParam String userId) {
        AddressBook records = iAddressBookService.lambdaQuery()
                .eq(StringUtils.isNotEmpty(userId), AddressBook::getUserId, userId)
                .eq(AddressBook::getIsDefault,1).list().get(0);
        return records;
    }

    /**
     * 通过userId和选中的地址id修改默认地址
     *
     */
    @GetMapping("updateDefault")
    public Boolean updateDefault(@RequestParam String userId,@RequestParam String selectId) {
        List<AddressBook> records = iAddressBookService.lambdaQuery()
                .eq(StringUtils.isNotEmpty(userId), AddressBook::getUserId, userId).list();
        records.forEach(addressBook -> {
            if(addressBook.getId().equals(selectId)){
                addressBook.setIsDefault(1);
            }else{
                addressBook.setIsDefault(0);
            }
            iAddressBookService.updateById(addressBook);
        });

        return null;
    }


}
